<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="./vue.js"></script>
</head>
<!-- 2. https://www.jq22.com/yanshi24087 滚动条 -->

<body style="height: 300vh;">
    <div id="app">
        <div class="progress-bar"
            style="position: fixed;top: 0;left: 0;width: 0%;height: 5px;background-color: #0026ff;transition: width 0.3s ease;">
        </div>
    </div>
</body>
<script>
    const { createApp, ref, watch, onMounted } = Vue;
    const app = createApp({
        setup() {
            let progressBar = ref('');
            let scrollTop = ref(0);
            let lastScrollTop = ref(0);

            onMounted(() => {
                progressBar.value = document.querySelector('.progress-bar');
            });

            // 监听滚动事件
            watch(() => scrollTop.value, (newValue, oldValue) => {
                if (newValue > oldValue) {
                    // 页面向下滚动时，进度条前进
                    if (progressBar.value) {
                        const scrollHeight = document.documentElement.scrollHeight - document.documentElement.clientHeight;
                        const progress = ((newValue - oldValue) / scrollHeight) * 100;
                        const newWidth = Math.min(progressBar.value.style.width.replace('%', '') * 1 + progress, 100) + '%';
                        progressBar.value.style.width = newWidth;
                    }
                } else {
                    // 页面向上滚动时，进度条回退
                    if (progressBar.value) {
                        const scrollHeight = document.documentElement.scrollHeight - document.documentElement.clientHeight;
                        const progress = ((oldValue - newValue) / scrollHeight) * 100;
                        const newWidth = Math.max(progressBar.value.style.width.replace('%', '') * 1 - progress, 0) + '%';
                        progressBar.value.style.width = newWidth;
                    }
                }
                lastScrollTop.value = newValue;
            });

            // 绑定滚动事件
            window.addEventListener('scroll', () => {
                scrollTop.value = document.documentElement.scrollTop;
            })

            return {
                progressBar
            }
        }
    }).mount('#app')
</script>

</html>